import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { ACCESS_TOKEN, MENU_NAV, PERMISSION, ROLE, USER_INFO } from '@/store/mutation-types'
import ls from '@/utils/Storage'
import { setDocumentTitle } from '@/utils/domUtil'
import versionTood from '@/utils/versionUpdate.js'
import type { Router } from 'vue-router'
import { layoutMode } from '@/store/useSiteSettings'
import { findMenuByPath } from '@/utils/menu'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
import { getAppByPath, toggleApp } from '@/utils/app'
const whiteList = ['login', 'register', 'registerResult'] // 不进行拦截的路由名称集合
const notApp = ['appSelect']
import { currentApp } from '@/store/useSiteSettings'
import generateAsyncRoutes from '@/router/generateAsyncRoutes'
import { clearUserInfo } from '@/utils/util'
import { GET } from '@/api/api'
export const setupBeforeEach = (router: Router) => {
  router.beforeEach((to, from, next) => {
    versionTood.isNewVersion()
    NProgress.start() // 加载进度条
    setDocumentTitle(to)
    if (whiteList.includes(to.name as any)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      if (ls.get(ACCESS_TOKEN) && ls.get(PERMISSION)) {
        if (to.path === '/') {
          next({ path: '/appSelect' })
          NProgress.done()
        } else {
          if (notApp.includes(to.name as any)) {
            next()
          } else {
            const pathApp = getAppByPath(to.path)
            if (pathApp !== currentApp.value) {
              console.log('is切换,,,,,,')
              toggleApp(pathApp)
                .then((app) => {
                  router.push(to.path)
                })
                .catch((e) => {
                  router.push('/portal')
                })
            } else {
              const menus = ls.get(MENU_NAV)[currentApp.value]
              const root = findMenuByPath(menus, to.fullPath)
              if (root && root.meta && root.meta.query) {
                to.query = root.meta.query
              }
              if (layoutMode.value == 'mixmenu') {
                const getFirstChild = (routes) => {
                  const route = routes[0]
                  if (!route.children || route.children.length === 0) {
                    return route
                  }
                  return getFirstChild(route.children)
                }
                if (root && root.children && root.children.length > 0) {
                  const child = getFirstChild(root.children)
                  next({ path: child.fullPath })
                } else {
                  next()
                }
              } else {
                next()
              }
            }
          }
        }
      } else {
        const query = to.query
        if (query && query.token) {
          ls.set(ACCESS_TOKEN, query.token)
          const all = [
            GET('/authority/security/permissionSet'),
            GET('/realm/mine/info'),
            GET('/menu/mine/list?app=portal')
          ]
          Promise.all(all)
            .then((allRes) => {
              ls.set(PERMISSION, allRes[0].data.permissions)
              ls.set(ROLE, allRes[0].data.roles)
              ls.set(USER_INFO, allRes[1].data)
              generateAsyncRoutes(router, { portal: allRes[2].data })
              router.push(to.path)
            })
            .catch((e) => {
              clearUserInfo()
              next({ path: '/user/login' })
            })
        } else {
          next({ path: '/user/login' })
        }
      }
    }
  })
}

export const setupAfterEach = (router: Router) => {
  router.afterEach(() => {
    NProgress.done() // finish progress bar
  })
}
